import './ShopCard.scss'
import { AddCircleOutline, DeleteOutline, GiftOutline, MinusCircleOutline } from 'antd-mobile-icons'
import { Image, Mask, Modal, Toast } from 'antd-mobile'
import { useMemo, useState, } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { addCartList, clearShopCartItem, disCartList } from '../../../../../store/modules/cart'
import type { RootState } from '../../../../../store'
import type { Commodity } from '../../../../../api/shops'
import { useNavigate } from 'react-router-dom'
import {  addOrderSubOrderList, addOrderSubShopInfo } from '../../../../../store/modules/orderSubmit'

type Props = {
    shops_id: string,
    delivery_fee?: number
}

const ShopCard = (
    { shops_id, delivery_fee = 0 }: Props
) => {
    const navigate = useNavigate()
    const dispatch = useDispatch()


    const CartList = useSelector((state: RootState) => {
        // 双重安全校验：
        // - 若 state.cartShop 不存在，视为空对象
        // - 若 shops_id 对应的购物车不存在，返回空数组
        return (state.cart.cartShop || {})[shops_id] || [];
    });
const shopInfo = useSelector((state:RootState)=>{
   const index= state.shops.Shops.findIndex((item)=>{
        return item._id ===shops_id
    })
   return state.shops.Shops[index]
}) 
    

        const [showCard, setShowCard] = useState(false)


        const cartCount = useMemo(() => {
            return CartList.reduce((total, item) => total + item.count, 0)
        }, [CartList])
        const cartPrice = useMemo(() => {
            return CartList.reduce((total, item) => total + item.count * item.discount_price, 0) + delivery_fee
        }, [CartList, delivery_fee])
        const isCart = useSelector((state: RootState) => {
            if (state.cart.cartShop[shops_id]) {
                if (state.cart.cartShop[shops_id].length) {
                    return true
                }

            }
            return false
        })
        const showCart = () => {
            if (isCart) {
                setShowCard(!showCard)
            }

        }
        const clearCard = () => {
            Modal.confirm({
                content: '是否清空购物车？',
                onConfirm: () => {
                    dispatch(clearShopCartItem({ shops_id }))
                    setShowCard(false)
                }
            })

        }
        const addCart = (item: Commodity) => {

            dispatch(addCartList({ commodity: item, shops_id: shops_id }))
        }
        const disCart = (commodity_id: string) => {

            dispatch(disCartList({ shops_id, commodity_id }))
        }

        const navPayOrder = () => {

            if (CartList.length) {
                dispatch(addOrderSubShopInfo(shopInfo))
                dispatch(addOrderSubOrderList(CartList))
                navigate(`/payorder?shops_id=${shops_id}`)
            } else {
                Toast.show({
                    content: '购物车为空！'
                })
            }
        }

        return <div className='card'>
            <Mask className='mask' visible={showCard} onMaskClick={() => setShowCard(false)}>
                <div className='cardList' >
                    <div className='blod'>
                        已加购商品
                    </div>
                    <div className='del' onClick={clearCard}>
                        <DeleteOutline width={30} height={30} />
                    </div>
                    <div className='soall'>
                        {
                            CartList.map(item => (
                                <div className='cardItem' key={item._id}>
                                    <div className='productAvatar'>
                                        <Image src={item.imgUrl} style={{ borderRadius: 10 }} width={60} height={60} />
                                    </div>
                                    <div className='productInfo'>
                                        <div className='title'>
                                            {item.name}
                                        </div>
                                        <div className='detail'>
                                            {item.desc}
                                        </div>
                                        <div className="price">
                                            <span>{item.price}</span>￥{item.discount_price}
                                        </div>
                                    </div>
                                    <div className='add_minus'>
                                        <div className="minus" onClick={() => disCart(item._id)}>
                                            <MinusCircleOutline color="blue" width={20} height={20} />
                                        </div>
                                        <div>{item.count}</div>
                                        <div className="add" onClick={() => addCart(item)} >
                                            <AddCircleOutline color="#ED7C3C" width={20} height={20} />
                                        </div>
                                    </div>
                                </div>
                            ))
                        }
                    </div>
                    <div className='subtotal'>
                        {delivery_fee === 0 ?
                            <div className='cardDelivery'>免配送费</div> :
                            <div className='cardDelivery'>配送费：<span style={{ color: 'red' }}>{delivery_fee}￥</span></div>
                        }
                        <div className='cardCount'>  总计:<span className='count'>{cartCount}</span>件</div>
                        <div className='cardPrice'> 总价：<span className='price' >{cartPrice}￥</span></div>
                    </div>

                </div>
            </Mask>





            <div className='feixd'>
                <div className="shopCard_orders">
                    <div className="shopCard" onClick={() => showCart()}>
                        <GiftOutline width={50} height={50} color="#F7D200" />
                        <div className="num">{cartCount}</div>
                    </div>
                    <div className="orders" onClick={() => navPayOrder()}>
                        立即下单
                    </div>
                </div>
            </div>


        </div>
    }

export { ShopCard }